﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Trebuchet
{
    public class Preferences
    {
        private int hotKeyModifiers;

        public int HotKeyModifiers
        {
            get { return hotKeyModifiers; }
            set { hotKeyModifiers = value; }

        }

        private char hotKey;

        public char HotKey
        {
            get { return hotKey; }
            set { hotKey = value; }
        }

        public void Save()
        {
            string filename = string.Format("{0}\\{1}", Application.LocalUserAppDataPath, "Preferences.xml");
            MemoryStream stream = new MemoryStream();
            XmlSerializer xs = new XmlSerializer(this.GetType());
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
            xs.Serialize(writer, this);
            stream = (MemoryStream)writer.BaseStream;

            UTF8Encoding encoding = new UTF8Encoding();
            string returnString = encoding.GetString(stream.ToArray());
            TextWriter textWriter = new StreamWriter(filename);
            textWriter.WriteLine(returnString);
            textWriter.Close();
        }

        public static Preferences Read()
        {
            string filename = string.Format("{0}\\{1}", Application.LocalUserAppDataPath, "Preferences.xml");
            if (File.Exists(filename))
            {
                try
                {
                    TextReader reader = new StreamReader(filename);
                    string xml = reader.ReadToEnd();
                    reader.Close();

                    XmlSerializer xs = new XmlSerializer(typeof(Preferences));
                    UTF8Encoding encoding = new UTF8Encoding();
                    byte[] byteArray = encoding.GetBytes(xml);
                    MemoryStream stream = new MemoryStream(byteArray);
                    XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                    Object myObject = xs.Deserialize(stream);
                    Preferences preferences = (Preferences)myObject;
                    return preferences;
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
    }
}
